package com.besttone.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Filename: DateUtil.java<br>
 * Ttitle: <br>
 * Description: <br>
 * Author: zhengzhezhen
 */
public class DateUtil {
    public static final int SECONDS_ONE_MINUTE = 60;
    public static final int MILLISECONDS_ONE_SECOND = 1000;
    public static final int SECONDS_ONE_HOUR = 3600;
    public static final int SECONDS_ONE_DAY = 86400;
    public static final int DB_STORE_DATE = 1;
    public static final int HYPHEN_DISPLAY_DATE = 2;
    public static final int DOT_DISPLAY_DATE = 3;
    public static final int CN_DISPLAY_DATE = 4;
    public static final String DB_STORE_DATE_BEGIN = "000000";
    public static final String DB_STORE_DATE_END = "235959";

    public static Date getCurrDate(String formatStr) {
	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	String dateStr = sdf.format(new Date());
	Date date = new Date();
	try {
	    date = sdf.parse(dateStr);
	} catch (ParseException e) {
	    e.printStackTrace();
	}
	return date;
    }

    public static Date getCurrentDate() {
	String formatStr = "yyyy-MM-dd HH:mm:SS";
	return getCurrDate(formatStr);
    }

    public static String getCurrTime(String formatStr) {
	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(new Date());
    }

    public static Date getCurMonthFirstDate() {
	Calendar calendar = Calendar.getInstance();
	calendar.set(5, calendar.getActualMinimum(5));
	return calendar.getTime();
    }

    public static Date getCurMonthLastDay() {
	Calendar calendar = Calendar.getInstance();
	calendar.set(5, calendar.getActualMaximum(5));
	return calendar.getTime();
    }

    public static String getStoreDateBegin(String storeDate) {
	if (storeDate.length() >= 8) {
	    return storeDate.substring(0, 8) + "000000";
	}
	return storeDate;
    }

    public static String getStoreDateEnd(String storeDate) {
	if (storeDate.length() >= 8) {
	    return storeDate.substring(0, 8) + "235959";
	}
	return storeDate;
    }

    public static String getCurrTimeStr(int formatType) {
	return getTimeStr(new Date(), formatType);
    }

    /**
     * 获取是时间字符串
     * */
    public static String getTimeStr(Date date, int formatType) {
	if ((formatType < 1) || (formatType > 5)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMMddHHmmss";
	    break;
	case 2:
	    formatStr = "yyyy'-'MM'-'dd HH:mm:ss";
	    break;
	case 3:
	    formatStr = "yyyy.MM.dd HH:mm:ss";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'dd HH:mm:ss";
	    break;
	case 5:
	    formatStr = "yyyyMMddHHmmssSSS";
	    break;
	default:
	    formatStr = "yyyyMMddHHmmss";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(date);
    }

    public static String getCurrDateStr(int formatType) {
	return getDateStr(new Date(), formatType);
    }

    public static String getDateStr(Date date, int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMMdd";
	    break;
	case 2:
	    formatStr = "yyyy-MM-dd";
	    break;
	case 3:
	    formatStr = "yyyy.MM.dd";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'dd";
	    break;
	default:
	    formatStr = "yyyyMMdd";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(date);
    }

    public static String getYearMonthStr(int formatType) {
	return getYearMonthStr(new Date(), formatType);
    }

    public static String getYearMonthStr(Date date, int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMM";
	    break;
	case 2:
	    formatStr = "yyyy-MM";
	    break;
	case 3:
	    formatStr = "yyyy.MM";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'";
	    break;
	default:
	    formatStr = "yyyyMM";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(date);
    }

    public static String toVisualString(String sourceStr) {
	if ((sourceStr == null) || (sourceStr.equals(""))) {
	    return "";
	}
	return sourceStr;
    }

    public static String toDisplayStr(String dateStr, int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	if ((dateStr == null) || (dateStr.length() < 6)
		|| (dateStr.length() > 14) || (formatType == 1)) {
	    return toVisualString(dateStr);
	}
	char[] charArr = null;
	switch (formatType) {
	case 2:
	    charArr = new char[] { '-', '-', ' ', ':', ':' };
	    break;
	case 3:
	    charArr = new char[] { '.', '.', ' ', ':', ':' };
	    break;
	case 4:
	    charArr = new char[] { '年', '月', ' ', ':', ':' };
	    break;
	default:
	    charArr = new char[] { '-', '-', ' ', ':', ':' };
	}
	try {
	    SimpleDateFormat sdf1 = null;
	    SimpleDateFormat sdf2 = null;
	    switch (dateStr.length()) {
	    case 6:
		sdf1 = new SimpleDateFormat("yyyyMM");
		sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM");
		break;
	    case 8:
		sdf1 = new SimpleDateFormat("yyyyMMdd");
		sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'"
			+ charArr[1] + "'dd");
		break;
	    case 10:
		sdf1 = new SimpleDateFormat("yyyyMMddHH");
		sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'"
			+ charArr[1] + "'dd'" + "+charArr[2]" + "'HH");

		break;
	    case 12:
		sdf1 = new SimpleDateFormat("yyyyMMddHHmm");
		sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'"
			+ charArr[1] + "'dd'" + charArr[2] + "'HH'"
			+ charArr[3] + "'mm");

		break;
	    case 14:
		sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
		sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'"
			+ charArr[1] + "'dd'" + charArr[2] + "'HH'"
			+ charArr[3] + "'mm'" + charArr[4] + "'ss");

		break;
	    case 7:
	    case 9:
	    case 11:
	    case 13:
	    default:
		return dateStr;
	    }
	    return sdf2.format(sdf1.parse(dateStr));
	} catch (ParseException ex) {
	}
	return dateStr;
    }

    public static String toStoreStr(String dateStr) {
	if ((dateStr == null) || (dateStr.trim().equals(""))) {
	    return "";
	}
	StringBuffer strBuf = new StringBuffer();
	for (int i = 0; i < dateStr.length(); i++) {
	    if ((dateStr.charAt(i) >= '0') && (dateStr.charAt(i) <= '9')) {
		strBuf.append(dateStr.charAt(i));
	    }
	}
	return strBuf.toString();
    }

    public static String birthdayToAge(String birthdayStr) {
	if ((birthdayStr == null) || (birthdayStr.length() < 6)) {
	    return "";
	}
	int birthYear = Integer.parseInt(birthdayStr.substring(0, 4));
	int birthMonth = Integer.parseInt(birthdayStr.substring(4, 6));
	Calendar cal = new GregorianCalendar();
	int currYear = cal.get(1);
	int currMonth = cal.get(2);
	int age = currYear - birthYear;
	age -= (currMonth < birthMonth ? 1 : 0);
	return "" + age;
    }

    public static String add(String dateTimeStr, int formatType, int detal,
	    int field) {
	if ((dateTimeStr == null) || (dateTimeStr.length() < 6))
	    return dateTimeStr;
	try {
	    String formatStr = null;
	    switch (formatType) {
	    case 1:
		formatStr = "yyyyMMddHHmmss";
		break;
	    case 2:
		formatStr = "yyyy-MM-dd HH:mm:ss";
		break;
	    case 3:
		formatStr = "yyyy.MM.dd HH:mm:ss";
		break;
	    case 4:
		formatStr = "yyyy'年'MM'月' HH：mm：ss";
		break;
	    default:
		formatStr = "yyyyMMddHHmmss";
	    }

	    formatStr = formatStr.substring(0, dateTimeStr.length());
	    SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	    Date d = sdf.parse(dateTimeStr);
	    GregorianCalendar g = new GregorianCalendar();
	    g.setTime(d);
	    g.add(field, detal);
	    d = g.getTime();
	    return sdf.format(d);
	} catch (ParseException ex) {
	    ex.printStackTrace();
	}
	return dateTimeStr;
    }

    public static String getDateFormat(Date date, String outFmt) {
	if (null == date) {
	    return null;
	}
	String newOutFmt = outFmt;

	if ((null == newOutFmt) || ("".equals(newOutFmt.trim()))) {
	    newOutFmt = "yyyyMMdd";
	}

	String retu = null;
	SimpleDateFormat dateFormat = null;
	try {
	    dateFormat = new SimpleDateFormat(newOutFmt);
	} catch (IllegalArgumentException iaex) {
	    dateFormat = new SimpleDateFormat("yyyyMMdd");
	}
	retu = dateFormat.format(date);

	dateFormat = null;

	return retu;
    }

    public static String getDateFormat(Date date) {
	return getDateFormat(date, "yyyyMMdd");
    }

    public static String getDateFormatByFmt(Date date, String outFmt) {
	return getDateFormat(date, outFmt);
    }

    public static String getDateFormat(String outFmt) {
	return getDateFormat(new Date(), outFmt);
    }

    public static String getDateFormat() {
	return getDateFormat(new Date(), "yyyyMMdd");
    }

    public static String getDateFormat(long millis, String outFmt) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTimeInMillis(millis);

	String retu = getDateFormat(calendar.getTime(), outFmt);
	calendar = null;
	return retu;
    }

    public static String getDateFormat(String datestr, String inFmt,
	    String outFmt) throws ParseException {
	if ((null == datestr) || ("".equals(datestr.trim()))) {
	    return datestr;
	}

	if ((null == inFmt) || ("".equals(inFmt.trim()))) {
	    return datestr;
	}

	String newOutFmt = outFmt;
	if ((null == newOutFmt) || ("".equals(newOutFmt.trim()))) {
	    newOutFmt = "yyyyMMdd";
	}

	Date inDate = getDate(datestr, inFmt);

	if (null == inDate) {
	    return datestr;
	}

	String retu = getDateFormat(inDate, newOutFmt);
	inDate = null;
	return retu;
    }

    public static String getDateFormat(String datestr, String inFmt)
	    throws ParseException {
	return getDateFormat(datestr, inFmt, "yyyyMMdd");
    }

    public static Date getDate(String datestr, String inFmt) {
	if ((null == datestr) || ("".equals(datestr.trim()))) {
	    return null;
	}

	String newInFmt = inFmt;
	if ((null == newInFmt) || ("".equals(newInFmt.trim()))) {
	    newInFmt = "yyyyMMdd";
	}

	if (inFmt.contains("-"))
	    datestr = datestr.replaceAll("年", "-").replaceAll("月", "-");
	else if (inFmt.contains("年")) {
	    datestr = datestr.replace("-", "年").replace("-", "月");
	}

	Date inDate = null;

	SimpleDateFormat inDateFormat = new SimpleDateFormat(newInFmt);
	inDateFormat.setLenient(true);

	try {
	    inDate = inDateFormat.parse(datestr);
	} catch (ParseException e) {
	    e.printStackTrace();
	}

	inDateFormat = null;
	return inDate;
    }

    public static int dateDiff(Date date1, Date date2) {
	if (date1.compareTo(date2) == 0) {
	    return 0;
	}
	long second = (date1.getTime() - date2.getTime()) / 1000L;
	return (int) (second / 86400L);
    }

    public static int dateDiff(String dateStr1, String dateStr2, String inFmt) {
	Date date1 = null;
	Date date2 = null;
	try {
	    date1 = getDate(dateStr1, inFmt);
	    date2 = getDate(dateStr2, inFmt);
	} catch (Exception e) {
	    return -1;
	}

	return dateDiff(date1, date2);
    }

    public static Date addDate(Date date, int calendarField, int amount) {
	if (null == date) {
	    return date;
	}
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	calendar.add(calendarField, amount);
	return calendar.getTime();
    }

    public static Date addDate(String datestr, int calendarField, int amount) {
	return addDate(getDate(datestr, "yyyyMMdd"), calendarField, amount);
    }

    private static int getInt(String intStr, int intDef) {
	if ((null == intStr) || ("".equals(intStr.trim()))) {
	    return intDef;
	}

	int intRetu = intDef;

	Double db = new Double(intStr);
	intRetu = db.intValue();
	return intRetu;
    }

    public static int getAge(Date birthday, Date date2) {
	if ((null == birthday) || (null == date2)) {
	    return -1;
	}

	if (birthday.after(date2)) {
	    return -1;
	}

	int ibdYear = getInt(getDateFormat(birthday, "yyyy"), -1);
	int idate2Year = getInt(getDateFormat(date2, "yyyy"), -1);

	if ((ibdYear < 0) || (idate2Year < 0)) {
	    return -1;
	}
	if (ibdYear > idate2Year) {
	    return -1;
	}

	return idate2Year - ibdYear + 1;
    }

    public static int getAge(Date birthday) {
	return getAge(birthday, new Date());
    }

    public static int getAge(String birthdaystr) throws ParseException {
	return getAge(getDate(birthdaystr, "yyyyMMdd"));
    }

    public static String getCurrTime(int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMMddHHmmss";
	    break;
	case 2:
	    formatStr = "yyyy'-'MM'-'dd HH:mm:ss";
	    break;
	case 3:
	    formatStr = "yyyy.MM.dd HH:mm:ss";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'dd HH:mm:ss";
	    break;
	default:
	    formatStr = "yyyyMMddHHmmss";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(new Date());
    }

    public static String getCurrDate(int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMMdd";
	    break;
	case 2:
	    formatStr = "yyyy-MM-dd";
	    break;
	case 3:
	    formatStr = "yyyy.MM.dd";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'dd";
	    break;
	default:
	    formatStr = "yyyyMMdd";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(new Date());
    }

    public static String getYearMonth(int formatType) {
	if ((formatType < 1) || (formatType > 4)) {
	    throw new IllegalArgumentException("时间格式化类型不是合法的值。");
	}
	String formatStr = null;
	switch (formatType) {
	case 1:
	    formatStr = "yyyyMM";
	    break;
	case 2:
	    formatStr = "yyyy-MM";
	    break;
	case 3:
	    formatStr = "yyyy.MM";
	    break;
	case 4:
	    formatStr = "yyyy'年'MM'月'";
	    break;
	default:
	    formatStr = "yyyyMM";
	}

	SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
	return sdf.format(new Date());
    }

    public static long getTimeValue(String datetime, String inFmt)
	    throws ParseException {
	return getDate(datetime, inFmt).getTime();
    }

    public static String getTimeStr(long milliSeconds, int formatType) {
	Date d = new Date(milliSeconds);
	return getTimeStr(d, formatType);
    }

    public static String[] getLastMonthBetweenDay(Date time) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(time);
	int year = 0;
	int month = cal.get(2) - 1;
	if (month == 0) {
	    year = cal.get(1) - 1;
	    month = 12;
	} else {
	    year = cal.get(1);
	}
	Calendar c = Calendar.getInstance();
	c.set(year, month, 1);
	int startDay = c.getActualMinimum(5);
	int endDay = c.getActualMaximum(5);
	c.set(year, month, startDay);
	String startTime = getDateFormat(c.getTime());
	c.clear();
	c.set(year, month, endDay);
	String endTime = getDateFormat(c.getTime());
	return new String[] { startTime, endTime };
    }

    public static String[] getLastMonthBetweenDayByFmt(Date time, String fmt) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(time);
	int year = 0;
	int month = cal.get(2) - 1;
	if (month == 0) {
	    year = cal.get(1) - 1;
	    month = 12;
	} else {
	    year = cal.get(1);
	}
	Calendar c = Calendar.getInstance();
	c.set(year, month, 1);
	int startDay = c.getActualMinimum(5);
	int endDay = c.getActualMaximum(5);
	c.set(year, month, startDay);
	String startTime = getDateFormatByFmt(c.getTime(), fmt);
	c.clear();
	c.set(year, month, endDay);
	String endTime = getDateFormatByFmt(c.getTime(), fmt);
	return new String[] { startTime, endTime };
    }

    public static String getTimeBetweenStr(String beginTime, String endTime,
	    String inFmt) {
	SimpleDateFormat dfs = new SimpleDateFormat(inFmt);
	StringBuffer timeStrBuf = new StringBuffer();
	try {
	    Date begin = dfs.parse(beginTime);
	    Date end = dfs.parse(endTime);
	    if (begin.compareTo(end) == 0) {
		return "1秒";
	    }
	    long between = (end.getTime() - begin.getTime()) / 1000L;
	    if (between < 0L) {
		timeStrBuf.append("-");
		between = -between;
	    }
	    long day = between / 86400L;
	    long hour = between % 86400L / 3600L;
	    long minute = between % 3600L / 60L;
	    long second = between % 60L;
	    if (day != 0L) {
		timeStrBuf.append(String.valueOf(day) + "天");
	    }
	    if (hour != 0L) {
		timeStrBuf.append(String.valueOf(hour) + "时");
	    }

	    if (minute != 0L) {
		timeStrBuf.append(String.valueOf(minute) + "分");
	    }
	    if (second != 0L)
		timeStrBuf.append(String.valueOf(second) + "秒");
	} catch (Exception e) {
	    return null;
	}
	return timeStrBuf.toString();
    }

    public static Date add(Date date, int field, int amount) {
	if (date == null) {
	    date = new Date();
	}

	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	cal.add(field, amount);

	return cal.getTime();
    }

    public static Date addMilliSecond(Date date, int amount) {
	return add(date, 14, amount);
    }

    public static Date addSecond(Date date, int amount) {
	return add(date, 13, amount);
    }

    public static Date addMiunte(Date date, int amount) {
	return add(date, 12, amount);
    }

    public static Date addHour(Date date, int amount) {
	return add(date, 10, amount);
    }

    public static Date addDay(Date date, int amount) {
	return add(date, 5, amount);
    }

    public static Date addMonth(Date date, int amount) {
	return add(date, 2, amount);
    }

    public static Date addYear(Date date, int amount) {
	return add(date, 1, amount);
    }

    private DateUtil() {
    }

    public static Date getDate(String dateStr) {
	Date temp1 = null;
	if (dateStr == null)
	    return null;
	if (dateStr.equals(""))
	    return null;
	SimpleDateFormat formatter = null;
	try {
	    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    temp1 = formatter.parse(dateStr);
	} catch (Exception e) {
	    try {
		formatter = new SimpleDateFormat("yyyy-MM-dd");
		temp1 = formatter.parse(dateStr);
	    } catch (Exception e1) {
		try {
		    formatter = new SimpleDateFormat("yyyy/MM/dd");
		    temp1 = formatter.parse(dateStr);
		} catch (Exception e2) {
		    e2.printStackTrace();
		}
	    }
	}
	return temp1;
    }

    public static String getDateTimeStr() {
	String str = null;
	try {
	    java.text.DateFormat format = new SimpleDateFormat(
		    "yyyyMMddHHmmssSSS");
	    str = format.format(new Date());

	} catch (Exception e) {

	}
	return str;
    }

    public static String getDateStr() {
	java.text.DateFormat format = new SimpleDateFormat("yyyyMMdd");
	return format.format(new Date());
    }

    public static String getNextDate() {
	Calendar cal = Calendar.getInstance();
	Date date = new Date();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	try {
	    cal.setTime(date);
	    cal.add(cal.DATE, 1);
	    return sdf.format(cal.getTime());
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return "";
    }

    public static String getNextDate(String dateStr, int i) {
	Calendar cal = Calendar.getInstance();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	Date date = new Date();
	try {
	    date = sdf.parse(dateStr);
	} catch (ParseException e1) {
	}
	try {
	    cal.setTime(date);
	    cal.add(cal.DATE, i);
	    return sdf.format(cal.getTime());
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return "";
    }

    public static String getNextMonth() {
	Calendar cal = Calendar.getInstance();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
	Date date = new Date();
	try {
	    cal.setTime(date);
	    cal.add(cal.MONTH, 1);
	    return sdf.format(cal.getTime());
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return "";
    }

    public static String getDateStr(Date date) {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	return sdf.format(date);
    }

    public static boolean twoDateDistance(String dateStr) {

	if (dateStr == null || "".equals(dateStr)) {
	    return false;
	}
	SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
	Date startDate = new Date();
	try {
	    startDate = formatter.parse(dateStr);
	} catch (ParseException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	Date endDate = new Date();
	long timeLong = endDate.getTime() - startDate.getTime();
	// System.out.println(timeLong);
	if (timeLong > 20 * 1000)
	    return true;
	return false;

    }

    public static void main(String[] args) {

	String str = "mt_msgid,req_result,send_area_code,send_child_account,send_city_code,send_number,send_operator_code,send_parent_account,send_province_code,send_province_short_code,send_time,sms_content,target_area_code,target_city_code,target_number,target_operator_code,target_province_code,target_province_short_code";
	System.out.println(str.toLowerCase());
	;
    }

}
